package com.itheima.filter;

import com.itheima.utils.BaseContext;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //1.获取到请求路径
        String path = request.getRequestURI();

        //2.判断请求路径是否为登录接口，包含login，如果是，则放行
        if (path.contains("login")){
            log.info("登录接口，放行");
            filterChain.doFilter(request,response);
            return;
        }
        if (path.contains("register")){
            log.info("注册接口，放行");
            filterChain.doFilter(request,response);
            return;
        }
        if (path.contains("upload")){
            log.info("上传接口，放行");
            filterChain.doFilter(request,response);
            return;
        }

        //3.获取请求头中token
        String token = request.getHeader("token");
        //解析token获取用户id

        Integer userId = JwtUtils.getUserId(token);
        String name = JwtUtils.getName(token);
        BaseContext.setCurrentId(userId);
        BaseContext.setName(name);



        //4.判断请求头中是否有token，没有就返回未登录信息（401）
        if (token == null || token.isEmpty()){
            log.info("令牌为空，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //5.解析token，如果解析失败，则返回未登录信息（401）
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("令牌解析失败，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //6.校验通过方行
        log.info("令牌校验通过，放行");
        filterChain.doFilter(request,response);
    }
}
